import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:hm_pda_app/router/auth_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserInfo {
  final String userName;
  UserInfo({required this.userName});
  Map<String, dynamic> toJson() {
    return {'userName': userName};
  }
}

class TopHeader extends StatelessWidget implements PreferredSizeWidget {
  const TopHeader({super.key, required this.title, this.showBackButton = true});

  final String title;
  final bool? showBackButton;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text(title),
      automaticallyImplyLeading: showBackButton ?? true,
      backgroundColor: Colors.blue[600],
      foregroundColor: Colors.white,
      elevation: 2,
      actions: [
        Builder(
          builder: (context) => IconButton(
            icon: const Icon(Icons.menu),
            onPressed: () {
              Scaffold.of(context).openEndDrawer();
            },
          ),
        ),
      ],
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}

// 自定义抽屉组件 - 单独的组件
class CustomDrawer extends StatefulWidget {
  const CustomDrawer({super.key});

  @override
  State<CustomDrawer> createState() => _CustomDrawerState();
}

class _CustomDrawerState extends State<CustomDrawer> {
  UserInfo? userInfo;

  @override
  void initState() {
    super.initState();
    getUserInfoData();
  }

  Future<void> getUserInfoData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userInfoString = prefs.getString('userInfo');
      print('userInfoString--- $userInfoString');
      if (userInfoString != null) {
        final userInfoMap = jsonDecode(userInfoString);
        setState(() {
          userInfo = UserInfo(userName: userInfoMap['userName'] ?? '未知用户');
        });
      }
    } catch (e) {
      print('获取用户信息失败: $e');
      setState(() {
        userInfo = UserInfo(userName: '未知用户');
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      width: 280, // 设置抽屉宽度
      backgroundColor: Colors.grey[100], // 设置背景色
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          bottomLeft: Radius.circular(20),
        ),
      ),
      child: Column(
        children: [
          Container(
            height: 200,
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [Colors.blue, Colors.purple],
              ),
            ),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const CircleAvatar(
                    radius: 40,
                    backgroundImage: NetworkImage('https://picsum.photos/100'),
                  ),
                  const SizedBox(height: 10),
                  Text(
                    userInfo?.userName ?? '加载中...',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                 
                ],
              ),
            ),
          ),
          Expanded(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                ListTile(
                  leading: Icon(Icons.logout, color: Colors.red[600]),
                  title: const Text('退出登录'),
                  onTap: () async {
                    // 添加退出登录逻辑
                    Provider.of<AuthProvider>(context, listen: false).logout();
                    Navigator.of(
                      context,
                    ).pushNamedAndRemoveUntil('/Login', (route) => false);
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
